#include <list>
#include <iostream>
//#include <fstream>
#include <cstring>
//#include <string>
#include <stdio.h>

#include "cube.h"
#include "cubelist.h"

using namespace std;

int main(int argc,char *argv[])
{
	FILE* input;
	FILE* output;
	string temp;
	char temp1;

	char input_file_name[50];
	char output_file_name[50];
	char app0[15]= "-prime.pla";
	char app1[15] = "-essen1.pla";
	char app2[15] = "-essen2.pla";
	char arg[100];

	int i, flag;
//Generate input file name

/*
	for (i = 0; argv[1][i] != '\0'; i++)
		input_file_name[i] = argv[1][i];
	input_file_name[i] = '\0';
*/
	strcpy(input_file_name, argv[1]);

	input = fopen(input_file_name, "r");
	if (input == NULL){
		cout << "Cannot open input file\n";
		return -1;
	}

	strcpy(arg, argv[2]);

	if (arg[0] == '-' && arg[1] == 'p')
		flag = 0;
	else if (arg[0] == '-' && arg[1] == 'e' && arg[2] == '1')
		flag = 1;
	else if(arg[0] == '-' && arg[1] == 'e' && arg[2] == '2')
		flag = 2;
	else{
		cout << "-p for prime generation\n";
		cout << "-e1 for essential 1\n";
		cout << "-e2 for essential 2\n";
		return -1;
	}

	cout << "Reading input file: " << input_file_name << endl;
//Generate output file name
/*	for (i = 0; input_file_name[i] != '\0'; i++)
		output_file_name[i] = input_file_name[i];
	i = i - 4;
*/
	strcpy(output_file_name, input_file_name);

	i = 0;

	while(output_file_name[i] != '\0')
		i++;
	i = i - 4;
	output_file_name[i] = '\0';

	if (flag == 0)
		strcat(output_file_name, app0);
	else if (flag == 1)
		strcat(output_file_name, app1);
	else if (flag == 2)
		strcat(output_file_name, app2);

/*
	for (j = 0; j < 10; j++)
		output_file_name[i+j] = app0[j];
	output_file_name[i+j] = '\0';
*/

	output = fopen(output_file_name, "w");
	if (output == NULL)
	{
		cout << "Cannot open output file\n";
		return -1;
	}

//Start
	cubelist origin;
	int icount;

	temp1 = fgetc(input);
	while(temp1 != 'i'){
		temp1 = fgetc(input);
	}

	fscanf(input, "%d", &icount);
	origin.icount = icount;
	cout << "Input variables: " << origin.icount << endl;

	temp1 = fgetc(input);
	while(temp1 != 'o'){
		temp1 = fgetc(input);
	}

	temp1 = fgetc(input);
	while(temp1 != '\n'){
		temp1 = fgetc(input);
	}

	temp1 = fgetc(input);
	while (temp1 != '.'){
		temp.clear();
		while (temp1 != ' '){
			temp.push_back(temp1);
			temp1 = fgetc(input);
		}
		while(temp1 != '\n'){
			temp1 = fgetc(input);
		}
		cube new_cube(temp);
		cout << temp << endl;
		origin.cover.push_back(new_cube);
		while(temp1 != '\n'){
			temp1 = fgetc(input);
		}
		temp1 = fgetc(input);
	}

//	cout << "finish reading" << endl;
	for (int i = 0; i< origin.icount; i++)
		origin.index.push_back(i);

	if (flag == 0)
		origin.prime();
	else if (flag == 1)
		origin.essential1();
	else if (flag == 2)
		origin.essential2();

	origin.sort();

	origin.output(output);

	cout << "Writing output file: " << output_file_name << endl;
	fclose(input);
	fclose(output);

	return 0;
}
